import React, { useCallback } from 'react'
import { Flex, Button, WingBlank, WhiteSpace } from 'antd-mobile'
import { connect } from 'dva'
import router from 'umi/router'
import classNames from 'classnames'
import { createNamedAction } from 'Local/utils'

import { NAMESPACE } from './model'
import styles from './index.scss'

const createLocalAction = createNamedAction(NAMESPACE)

const Index = props => {
  const { dispatch } = props
  const {
    loading,
    progress,
    file,
    questions,
    questionsProgess
  } = props[NAMESPACE]

  const showEntry = !loading && !!questions.length

  let label = '选择excel文件'
  if (loading) {
    label = `读取中(${progress}%)`
  } else if (showEntry) {
    label = '重新选择excel文件'
  }

  const fileChangeHandle = useCallback(evt => {
    const { files } = evt.target
    if (!files.length) {
      return
    }
    dispatch(createLocalAction('fileChangeHandle')({
      file: files[0]
    }))
  }, [dispatch])

  const navToTestPage = useCallback(() => {
    router.push('/question')
  }, [])

  return (
    <>
      <Flex
        align='center'
        justify='center'
        className={classNames(
          styles.fullPageContainer
        )}
      >
        <div style={{ flex: 1 }}>
          <WingBlank>
            <label>
              <Button
                type={showEntry ? 'ghost' : 'primary'}
                loading={loading}
              >{label}</Button>

              <input
                className={classNames(styles.hidden)}
                type='file'
                accept='application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                value={file}
                onChange={fileChangeHandle}
              />
            </label>

            {
              showEntry
                ? (
                  <>
                    <WhiteSpace />
                    <Button
                      type='primary'
                      onClick={navToTestPage}
                    >{questionsProgess ? '继续答题' : '开始答题'}</Button>
                  </>
                )
                : null
            }
          </WingBlank>
        </div>
      </Flex>

      <div className={styles.buildTime}>
        {__BUILD_TIME__}
      </div>
    </>
  )
}

export default connect(state => ({
  [NAMESPACE]: state[NAMESPACE]
}))(Index)
